package cn.zx.controller;

import cn.zx.po.Cart;
import cn.zx.po.CartItem;
import cn.zx.po.Product;
import cn.zx.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.Session;
import javax.servlet.http.HttpSession;

/**
 * 购物车模块的Controller
 * Created by zzz on 2016/9/17.
 */
@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private ProductService productService;  //商品模块的Service


    /**
     * 将购物项添加到购物车
     * @return
     */
    @RequestMapping("/cart_addCart")
    public String addCart(@RequestParam(value = "count") Integer count,@RequestParam(value = "pid") Integer pid,HttpSession session) throws Exception{
        //封装一个购物项
        CartItem cartItem = new CartItem();
        //设置数量
        cartItem.setCount(count);
        //根据商品的pid查询商品
        Product product = productService.findByPid(pid);
        //设置商品信息
        cartItem.setProduct(product);
        //将购物项添加到购物车，购物车应该存入session中
        Cart cart = this.getCart(session);
        cart.addCart(cartItem);


        return "cart";
    }

    /**
     * 移动指定商品的购物项
     * @param pid
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/cart_removeCart")
    public String removeCart(@RequestParam(value = "pid") Integer pid,HttpSession session)throws Exception{
        Cart cart = this.getCart(session);
        cart.remove(pid);
        return "cart";
    }




    /**
     * 清空购物车
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/cart_clear")
    public String clearCart(HttpSession session) throws Exception{
        Cart cart = this.getCart(session);
        cart.clearCart();
        return "cart";
    }

    /**
     * 跳转到我的购物车
     * @return
     * @throws Exception
     */
    @RequestMapping("/cart_myCart")
    public String myCart()throws Exception{
        return "cart";
    }
    /**
     * 从session中获取购物车
     * @param session
     * @return
     * @throws Exception
     */
    private Cart getCart(HttpSession session)throws Exception{
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart == null){
            cart = new Cart();
            session.setAttribute("cart",cart);
        }
        return cart;
    }

}
